/*
 *   Copyright 2006 Wei Lian <lianwei3@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <dirent.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <linux/ptrace.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#include <gtk/gtk.h>
#include <sys/socket.h>
#include <netdb.h>
extern guint ptimer;
extern GtkWidget *labelplayer;
extern GtkWidget *buttonattach;
extern pid_t pidplayer;
extern char newurl[];
extern int tracing;
extern int detachflag;

pid_t
forkplayer (char *url)
{
  extern GtkWidget *entryplayer;

  GdkColor color;
  gdk_color_parse ("blue", &color);
  gtk_widget_modify_fg (labelplayer, GTK_STATE_ACTIVE, &color);

  pid_t pid;
  pid = fork ();
  if (pid == 0)
    {
      char *line, *playopt[16], *savept = NULL;
      int iter = 0;

      line = strdup (gtk_entry_get_text (GTK_ENTRY (entryplayer)));

      playopt[0] = strtok_r (line, " ,", &savept);
      while ((playopt[++iter] = strtok_r (NULL, " ,", &savept)) != NULL);

      playopt[iter] = url;
      playopt[++iter] = NULL;

      int fd = open ("/dev/zero", O_WRONLY);
      dup2 (fd, 1);
      dup2 (fd, 0);
      dup2 (fd, 2);
      execvp (playopt[0], playopt);
    }
  else if (pid > 0)
    return pid;
}

void
killplayer (pid_t pid)
{
  if (pid > 0)
    kill (pid, SIGTERM);
}

void
getdata (pid_t traced_process, long addr, char *str, int len)
{
  char *laddr;
  int i, j;
  union u
  {
    long val;
    char chars[sizeof (long)];
  } data;
  i = 0;
  j = len / sizeof (long);
  laddr = str;
  while (i < j)
    {
      if ((data.val = ptrace ((enum __ptrace_request) PTRACE_PEEKDATA,
			      traced_process, addr + i * 4, NULL)) == -1)
	{
	  perror ("ptrace peekdata 1");
	  detachflag = 1;
	  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (buttonattach),
					FALSE);
	}
      memcpy (laddr, data.chars, sizeof (long));
      ++i;
      laddr += sizeof (long);
    }
  j = len % sizeof (long);
  if (j != 0)
    {
      if ((data.val = ptrace ((enum __ptrace_request) PTRACE_PEEKDATA,
			      traced_process, addr + i * 4, NULL)) == -1)
	{
	  perror ("ptrace peekdata 2");
	  detachflag = 1;
	  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (buttonattach),
					FALSE);
	}
      memcpy (laddr, data.chars, j);

    }
  str[len] = '\0';
}

void
processSignal (int result, int status, pid_t traced_process)
{
  long orig_eax;
  long params[2];
  char *str;
  char *strtok, *strtok_buf;
  static int toggle = 0;

  ////status=1407(5):Trace Trap(process), 4991(19):Stop(continue), 3455(13):Broken Pipe(ptrace_continue)

  extern GtkTextIter cursor;
  extern GtkWidget *entrystatus;
  extern GtkTextBuffer *buffer;
  extern int readflag;

  if (WIFEXITED (status))	// || WIFSIGNALED (status))
    {
      if (result == pidplayer)
	{
	  pidplayer = -1;
	  GdkColor color;
	  gdk_color_parse ("black", &color);
	  gtk_widget_modify_fg (labelplayer, GTK_STATE_ACTIVE, &color);
	}
    }
  else if (WIFSTOPPED (status))
    {
      if (detachflag == 0 && readflag == 0)	///attached
	{
	  gtk_text_buffer_get_start_iter (buffer, &cursor);

	  int sig = WSTOPSIG (status);
	  switch (sig)
	    {
	    case SIGTRAP:
	      if ((orig_eax = ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				      traced_process, 4 * ORIG_EAX,
				      NULL)) == -1)
		perror ("ptrace peekuser orig_eax");
	      if (orig_eax == SYS_write)
		{
		  if (toggle == 0)
		    {
		      toggle = 1;

		      if ((params[0] =
			   ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				   traced_process, 4 * ECX, NULL)) == -1)
			perror ("ptrace peekuser ecx");
		      if ((params[1] =
			   ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				   traced_process, 4 * EDX, NULL)) == -1)
			perror ("ptrace peekuser edx");

		      str = (char *) malloc ((params[1] + 1) * sizeof (char));
		      getdata (traced_process, params[0], str, params[1]);

		      if ((strtok = strstr (str, "@LM_")) != 0)
			{
			  if (strstr (strstr (str, "@LM_") + 1, "@") != 0)
			    strtok =
			      strstr (strstr (str, "@LM_") + 1, "@") + 1;
			  gtk_text_buffer_insert (buffer, &cursor, strtok,
						  -1);

			  if (strstr (str, "@try to connect...") != 0)
			    gtk_entry_set_text (GTK_ENTRY (entrystatus),
						"try to connect...");

			  if (strstr (str, "@Resource Not Found!") != 0)
			    gtk_entry_set_text (GTK_ENTRY (entrystatus),
						"Resource Not Found!");
			}
		      else if (strstr (str, "http:") != 0)
			{
			  char *utf8_text;
			  utf8_text =
			    g_locale_to_utf8 (str, strlen (str), NULL, NULL,
					      NULL);
			  gtk_text_buffer_insert (buffer, &cursor, utf8_text,
						  -1);
			  ////strtok_r will change data!
			  strtok =
			    strtok_r (strstr (str, "http:"), "\">",
				      &strtok_buf);
			  strcpy (newurl, strtok);

			  strtok =
			    strtok_r (strstr (utf8_text, "<TITLE>") + 7, "<",
				      &strtok_buf);
			  gtk_entry_set_text (GTK_ENTRY (entrystatus),
					      strtok);

			}
		      free (str);
		    }
		  else
		    {
		      toggle = 0;
		    }
		}
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, NULL) == -1)
		perror ("ptrace sys 1");
	      break;

	    case SIGSTOP:
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, NULL) == -1)
		perror ("ptrace sys 3");
	      break;

	    default:		////SIGPIPE
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, sig) == -1)
		perror ("ptrace sys 2");
	    }
	}
      else			///detach
	{
	  if (ptrace
	      ((enum __ptrace_request) PTRACE_DETACH, traced_process,
	       NULL, NULL) == -1)
	    perror ("ptrace detach");
	  else
	    tracing = 0;

	  if (detachflag == 1 && readflag == 0 && tracing == 0)
	    {
	      gtk_entry_set_text (GTK_ENTRY (entrystatus), "detached");
	      gtk_text_buffer_set_text (buffer, "", -1);
	    }
	  else if (detachflag == 2 && tracing == 0)
	    {
	      g_source_remove (ptimer);
	      killplayer (pidplayer);
	      gtk_main_quit ();
	    }
	  else if (readflag == 1 && tracing == 0)	////test data availability
	    {
	      readflag = 0;

	      ////testing connect
	      int sock;
	      if ((sock =
		   try_connect (atoi
				(strstr (strstr (newurl, ":") + 1, ":") +
				 1))) > 0)
		////testing read
		if (try_read
		    (sock,
		     atoi (strstr (strstr (newurl, ":") + 1, ":") + 1)) == 0)
		  pidplayer = forkplayer (newurl);

	      if (detachflag == 0)
		////attach again
		if (ptrace
		    ((enum __ptrace_request) PTRACE_ATTACH, traced_process,
		     NULL, NULL) == -1)
		  perror ("ptrace attach 2");
		else
		  tracing = 1;
	      else
		{
		  gtk_entry_set_text (GTK_ENTRY (entrystatus), "detached2");
		  gtk_text_buffer_set_text (buffer, "", -1);
		}
	    }
	}
    }
}


#define READ_BUF_SIZE 256

long
find_pid_by_name (char *pidName, char *pidName2)
{
  DIR *dir;
  struct dirent *next;

  dir = opendir ("/proc");
  if (!dir)
    {
      fprintf (stderr, "Cannot open /proc\n");
      exit (1);
    }

  while ((next = readdir (dir)) != NULL)
    {
      FILE *status;
      char filename[READ_BUF_SIZE];
      char buffer[READ_BUF_SIZE];

      if (strcmp (next->d_name, "..") == 0)
	continue;

      if (!isdigit (*next->d_name))
	continue;

      sprintf (filename, "/proc/%s/cmdline", next->d_name);
      if (!(status = fopen (filename, "r")))
	{
	  continue;
	}

      int n;
      if ((n = fread (buffer, 1, sizeof buffer, status)) == 0)
	{
	  fclose (status);
	  continue;
	}
      fclose (status);

      int red = 0;

      while (red < n)
	{
	  if (strcmp (buffer + red, pidName) == 0)
	    {
	      red += strlen (buffer + red) + 1;
	      if (red >= n)
		break;
	      if (strcmp (buffer + red, pidName2) == 0)
		return strtol (next->d_name, NULL, 0);
	    }
	  red += strlen (buffer + red) + 1;
	}

    }
  return 0;
}

int
sound_read (int sound_handle)
{
  int result;
  if (ioctl (sound_handle, MIXER_READ (4), &result) == -1)
    {
      perror ("read_error");
      return -1;
    }
  result = ((result >> 8) + (result & 0xFF)) >> 1;
  result = (result > 0) ? result : 0;
  result = (result < 100) ? result : 100;
  return result;
}

void
sound_write (int sound_handle, int leftright)
{
  leftright = (leftright < 0) ? 0 : leftright;
  leftright = (leftright > 100) ? 100 : leftright;
  leftright = (leftright << 8) | (leftright & 0xFF);
  if (ioctl (sound_handle, MIXER_WRITE (4), &leftright) == -1)
    {
      perror ("write_error");
      return;
    }
}

int
socket_recv (int sock, char *buffer, int size, int timeout)
	////-2:timeout, -1:select err, -3:recv err, 0:server shutdown
{
  int ret, red = 0;
  fd_set fds;
  struct timeval tv;

  FD_ZERO (&fds);
  while (size)
    {
      if (timeout > 0)
	{
	  // Wait up to 'timeout' seconds for data on socket to be ready for read
	  FD_SET (sock, &fds);
	  tv.tv_sec = timeout;
	  tv.tv_usec = 0;
	  ret = select (sock + 1, &fds, NULL, NULL, &tv);
	  if (ret == -1)
	    {
	      printf ("select failed\n");
	      return -1;
	    }
	  if (ret != 1)
	    {
	      return -2;
	    }
	}

      ret = recv (sock, buffer + red, size, 0);
      if (ret == -1)
	{
	  printf ("RECV failed\n");
	  return -3;
	}
      /* Got zero bytes on blocking read.  For unix this is an 
         orderly shutdown. */
      if (ret == 0)
	{
//        printf ("recv recieved zero bytes!\n");
	  break;
	}
      red += ret;
      size -= ret;
    }
  return red;
}

int
socket_send (int sock, char *buffer, int size)
{
  int ret, sent = 0;

  while (size)
    {
      ret = send (sock, buffer + sent, size, 0);
      if (ret == -1)
	{
	  printf ("SEND failed\n");
	  return -1;
	}
      if (ret == 0)
	break;
      sent += ret;
      size -= ret;
    }
  return sent;
}

int
try_connect (int portnum)
{
  int sock;
  struct sockaddr_in serv_addr;
  struct hostent *server;
  ////

  server = gethostbyname ("127.0.0.1");
  if (server == NULL)
    {
      perror ("ERROR, no such host");
      return -2;
    }
  memset ((char *) &serv_addr, 0, sizeof (serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy ((char *) &serv_addr.sin_addr.s_addr,
	  (char *) server->h_addr, server->h_length);

  sock = socket (AF_INET, SOCK_STREAM, 0);
  if (sock == -1)
    {
      perror ("ERROR opening socket");
      return -3;
    }

  serv_addr.sin_port = htons (portnum);

  if (connect (sock, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) ==
      -1)
    {
      close (sock);
      return -1;
    }
  return sock;
}

int
try_read (int sock, int portnum)
{
  char str[320];
  sprintf (str,
	   "GET /live.asf HTTP/1.0\r\n"
	   "Host: 127.0.0.1:%d\r\n"
	   "Accept: */*\r\n"
	   "Accept-Language: en-us\r\n"
	   "Accept-Encoding: gzip, deflate\r\n"
	   "User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)\r\n"
	   "Connection: Keep-Alive\r\n\r\n", portnum);
  if (socket_send (sock, str, strlen (str)) == strlen (str))
    {
      if (socket_recv (sock, str, sizeof (str), 1) == sizeof (str))
	{
	  close (sock);
	  return 0;
	}
    }
  close (sock);
  return -1;
}
